package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.threadlocal.UserThreadLocalUtils;
import com.heima.file.service.MinioTemplate;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.wemedia.entity.WmMaterial;
import com.heima.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.wemedia.service.WmNewsMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.lang.invoke.LambdaMetafactory;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-02-15
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private MinioTemplate minioTemplate;
    /**
     * 图片上传
     * @param multipartFile
     * @return
     */
    @Override
    public String upload(MultipartFile multipartFile) {
//        从Theadlocal中获取userId
        Integer userId = UserThreadLocalUtils.getUserId();
//        获取后缀
        String suffix = StringUtils.substringAfterLast(multipartFile.getOriginalFilename(),".");
//        新文件名
        String fileName = UUID.randomUUID().toString() +"."+ suffix;
//        调用minio接口上传文件
        String url = "";
        try {
            url = minioTemplate.uploadImgFile(fileName, multipartFile.getInputStream());
        }catch (Exception e){
            log.error("上传文件失败！");
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }
        if(StringUtils.isBlank(url)){
            log.error("文件访问路径为空！");
            throw new LeadException(AppHttpCodeEnum.UPLOAD_ERROR);
        }
//        保存上传文件数据
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(userId);
        wmMaterial.setType(0);
        wmMaterial.setUrl(url);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection(false);
        save(wmMaterial);
        return url;
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto dto) {

        Integer userId = UserThreadLocalUtils.getUserId();
//        设置分页条件
        IPage<WmMaterial> iPage = new Page<>(dto.getPage(),dto.getSize());
//        设置查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmMaterial::getUserId,userId).
                eq(dto.getIsCollection()!=0,WmMaterial::getIsCollection,dto.getIsCollection());
//        分页查询
        IPage<WmMaterial> wmMaterialIPage = page(iPage, queryWrapper);
        if(CollectionUtils.isEmpty(wmMaterialIPage.getRecords())){
            log.info("没有查询到数据");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        返回对象
        return new PageResult<>(dto.getPage(),dto.getSize(),wmMaterialIPage.getTotal(),wmMaterialIPage.getRecords());
    }

    @Autowired
    private WmNewsMaterialService newsMaterialService;
    /**
     * 删除
     * @param materialId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delPic(Integer materialId) {
//        获取用户uid
        Integer userId = UserThreadLocalUtils.getUserId();
//        根据素材id检测素材是否被使用，查询文章素材中间
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,materialId);
        int count = newsMaterialService.count(queryWrapper);
        if(count>0){
//            素材被使用，不能删除
            log.error("素材被使用，不能删除");
            throw new LeadException(AppHttpCodeEnum.DATA_CAN_NOT_DEL);
        }

        LambdaQueryWrapper<WmMaterial> materialQueryWrapper = new LambdaQueryWrapper<>();
        materialQueryWrapper.eq(WmMaterial::getUserId,userId).eq(WmMaterial::getId,materialId);
//        查询素材
        WmMaterial wmMaterial = getOne(materialQueryWrapper);
        if(wmMaterial==null){
            log.error("素材不存在！");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String url = wmMaterial.getUrl();
        if(StringUtils.isBlank(url)){
            log.error("素材数据异常！");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        删除数据库
        remove(materialQueryWrapper);
//        删除minio
        minioTemplate.delete(url);
    }

    @Override
    public List<Integer> findByUrls(List<String> images) {
//        根据url集合查询对象集合
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmMaterial::getUrl,images);
        List<WmMaterial> wmMaterialList = list(queryWrapper);
//        如果部位空，获取id的集合
        if(!CollectionUtils.isEmpty(wmMaterialList)){
            List<Integer> ids = wmMaterialList.stream().map(WmMaterial::getId).collect(Collectors.toList());
            return ids;
        }
        return null;
    }
}
